﻿MPT.addAction("friend_follow", function(_elm) {

    var friend_jQ = $(_elm);
    var sort_jQ = $('.e_sort', _elm);
    var sort_list_jQ = $('.e_sort_list', _elm);
    var group_list_jQ = $('.e_group_list', _elm);
    var friend_list_jQ = $('.e_friend_list', _elm);
    var group_op_jQ = $('.e_group_op', _elm);
    var create_group_jQ = $('.e_create_group', _elm);
    var edit_group_jQ = $('.e_edit_group', _elm);
    var del_group_jQ = $('.e_del_group', _elm);
    var title_jQ = $('.e_title', _elm);
    var page_jQ = $('.e_page', _elm);
    var search_jQ = $('.e_search', _elm);
    var hd_jQs = $('.e_hd', _elm);

    var my_follow_jQ = $('.e_my_follow', _elm);
    var follow_me_jQ = $('.e_follow_me', _elm);
    var follow_each_jQ = $('.e_follow_each', _elm);

    var followGroupList, myFollowList;   //好友分组的列表
    var selected_ids;      //在对话框中选中的好友ID
    var order_type = 1;    //排序类型  
    var cur_group_id, cur_group_name;    //当前分组ID、当前分组名称

    //========================================关注分组列表、好友列表========================================

    //显示关注分组列表
    var displayGroupList = function(_callback) {
        Backend.findFollowGroupsWithCount(null, function(_resp) {
            if (Backend.resultValidate(_resp)) {
                followGroupList = SocialUtil.sortFollowGroup(_resp.data);
                myFollowList = followGroupList.result;

                group_list_jQ.empty();

                $.each(myFollowList, function(_i, _d) {
                    var group_jQ = $(MPT.getTmpl('one_follow_group', _d));
                    addActionGroup(group_jQ.get(), _d);
                    group_list_jQ.append(group_jQ);
                });

                if (_callback) { _callback(); };
            }
        });
    };


    //为每个关注分组添加事件
    var addActionGroup = function(_group_elm, _data) {
        $(_group_elm).click(function() {
            hd_jQs.removeClass('active');
            my_follow_jQ.addClass('active');
            cur_group_id = _data.groupID;
            cur_group_name = _data.groupName;
            displayManageGroup();
            displayFriendList(1);
        });
    };


    //显示好友列表
    var displayFriendList = function(_page_no) {

        var data = { "groupId": cur_group_id, "online": true, "shieldFlag": false, "pageNo": _page_no, "pageSize": 10, "type": 2, "orderType": order_type };

        Backend.findPerson(data, function(_resp) {

            if (Backend.pageBeanValidate(_resp)) {

                var friendList = _resp.results;
                friend_list_jQ.empty();

                $.each(friendList, function(_i, _d) {
                    var one_friend_jQ = $(MPT.getTmpl('one_follow', _d));
                    addActionFriend(one_friend_jQ.get(), _d);
                    friend_list_jQ.append(one_friend_jQ);
                });

                //显示分页
                var page_param = { "pageNo": _resp.pageNo, "pageSize": _resp.pageSize, "totalRecords": _resp.totalRecoreds, "totalPages": _resp.totalPages };
                var pageBar_jQ = (new Paginate).createPageBar(page_param, function(_click_page) {
                    displayFriendList(_click_page);
                });
                page_jQ.empty().append(pageBar_jQ);

            } else {
                friend_list_jQ.html('');
            }

        }, function() {
            friend_list_jQ.html('');
        });
    };

    //更新好友分组下的好友数量
    var updateGroupCount = function(_group_list) {
        $.each(_group_list, function(_i, _g) {
            var gid = _g.id;
            var delta = _g.delta;

            var group_jQ = group_list_jQ.find('a[gid=' + gid + ']');
            var pre_count = group_jQ.find('em').html();
            group_jQ.find('em').html(parseInt(pre_count) + parseInt(delta));
        });
    };

    //显示大组
    var addActionGroupTitle = function() {

        my_follow_jQ.click(function() {
            group_list_jQ.children().eq(0).click();
        });

        follow_me_jQ.click(function() {
            hd_jQs.removeClass('active');
            follow_me_jQ.addClass('active');
            title_jQ.text("我的粉丝");
            group_op_jQ.hide();
            cur_group_id = followGroupList.flwme.groupID;
            displayFriendList(1);
        });

        follow_each_jQ.click(function() {
            hd_jQs.removeClass('active');
            follow_each_jQ.addClass('active');
            title_jQ.text("相互关注");
            group_op_jQ.hide();
            cur_group_id = followGroupList.flweach.groupID;
            displayFriendList(1);
        });
    };


    //========================================每个好友========================================

    //为每条好友添加事件
    var addActionFriend = function(_people_elm, _data) {

        var people_jQ = $(_people_elm);
        var close_jQ = $('.e_close', _people_elm);
        var shield_jQ = $('.e_shield', _people_elm);
        var sh_icon_jQ = $('.e_sh_icon', _people_elm);
        var group_manage_jQ = $('.e_group_manage', _people_elm);

        var uid = people_jQ.attr('id');
        var nickname = people_jQ.attr('nick');
        var group_id = _data.groupID;

        var ginfo = { "groupID": _data.groupID, "groupName": _data.groupName, "groupList": myFollowList, "uid": _data.uid };

        var pre_group_ids;

        var getGroupIds = function() {
            var tempIds = $.map($(group_list_jQ.find('a[class*=on]')), function(n) {
                var gid = $(n).attr('gid');
                if (gid != followGroupList.all.groupID && gid != followGroupList.unsort.groupID) {
                    return gid;
                }
            });
            return tempIds.sort().join('$');
        }

        //修改分组、选择分组
        var group_jQ = SocialUtil.createModifyGroup(ginfo);
        var group_list_jQ = group_jQ.find('.e_group_list');


        group_jQ.hover(function() {
            group_jQ.addClass('active');
            group_list_jQ.show();

            pre_group_ids = getGroupIds();

        }, function() {
            group_jQ.removeClass('active');
            group_list_jQ.hide();

            var group_ids = getGroupIds();

            if (group_ids != pre_group_ids) {
                var data = { "follow_source_group": 0, "follow_target_group": group_ids, "targetUidStr": _data.uid };
                Backend.moveFollowGroupOneUserToMoreGroup(data, function(_resp) {
                    if (Backend.resultValidate(_resp)) {
                        Tip.show("分组修改成功");
                    } else {
                        Tip.show("分组修改失败");
                    }
                }, function() {
                    Tip.show("分组修改失败");
                });
            }
        });

        group_list_jQ.find('a').each(function(_i, _group_elm) {
            var group_jQ = $(_group_elm);
            group_jQ.click(function() {
                if (group_jQ.hasClass('on')) {
                    group_jQ.removeClass('on');
                } else {
                    group_jQ.addClass('on');
                }
            })
        });

        group_manage_jQ.append(group_jQ);

        //取消关注
        close_jQ.click(function() {
            var data = { "targetID": _data.uid };
            Backend.unfollow(data, function(_resp) {
                if (Backend.resultValidate(_resp)) {
                    //updateGroupCount([{ "id": group_id, "delta": -1 }, { "id": all_friend_id, "delta": -1}]);
                    people_jQ.fadeOut("fast", function() { $(this).remove(); });
                } else {
                    Tip.show("取消关注失败");
                }
            }, function() {
                Tip.show("取消关注失败");
            });
        });
    };


    //========================================弹出框好友列表操作========================================


    //弹出框中显示好友分组及好友列表
    var displayFriendDialog = function(_dlg) {

        var head_list_jQ = $('.e_head_list', _dlg);
        var group_select_jQ = $('.e_group_select', _dlg);
        var all_jQ = $('.e_all', _dlg);
        var selected_jQ = $('.e_selected', _dlg);
        var s_count_jQ = $('.e_s_count', _dlg);
        var html = [], selected_A = [];
        selected_ids = [];

        //每个头像的事件
        var addActionOnehead = function(_head_elm, _data) {
            var head_jQ = $(_head_elm);
            var avatar_jQ = $('.e_avatar', _head_elm);
            var hook_jQ = $('.e_hook', _head_elm);
            var uid = _data.uid;

            if ($.inArray(uid, selected_ids) != -1) {
                avatar_jQ.addClass('active');
                hook_jQ.addClass('hook');
            };

            head_jQ.click(function() {
                if ($.inArray(uid, selected_ids) != -1) {
                    avatar_jQ.removeClass('active');
                    hook_jQ.removeClass('hook');
                    s_count_jQ.text(parseInt(s_count_jQ.text()) - 1);
                    selected_ids = $.grep(selected_ids, function(n, i) { return n != uid });
                    selected_A = $.grep(selected_A, function(n, i) { return n.uid != uid });
                } else {
                    avatar_jQ.addClass('active');
                    hook_jQ.addClass('hook');
                    s_count_jQ.text(parseInt(s_count_jQ.text()) + 1);
                    selected_ids.push(uid);
                    selected_A.push(_data);
                }
            });
        };

        //分组添加数据
        $.each(myFollowList, function(_i, _d) {
            html.push('<option value="' + _d.groupID + '">' + _d.groupName + '</option>');
        });
        group_select_jQ.html(html.join(''));


        //切换分组
        group_select_jQ.change(function() {
            var gid = group_select_jQ.val();
            var data = { "groupId": gid, "online": false, "shieldFlag": false, "pageNo": 1, "pageSize": 20, "type": 2 };

            Backend.findPerson(data, function(_resp) {
                if (Backend.pageBeanValidate(_resp)) {
                    var friendList = _resp.results;
                    head_list_jQ.empty();

                    $.each(friendList, function(_i, _d) {
                        var one_head_jQ = $(MPT.getTmpl('one_head_dialog', _d));
                        addActionOnehead(one_head_jQ.get(), _d);
                        head_list_jQ.append(one_head_jQ);
                    });
                } else {
                    head_list_jQ.html('');
                }
            });
        });

        //点击“已选”
        selected_jQ.click(function() {
            group_select_jQ.attr("disabled", true);
            selected_jQ.addClass('active');
            all_jQ.removeClass('active');

            head_list_jQ.empty();
            $.each(selected_A, function(_i, _d) {
                var one_head_jQ = $(MPT.getTmpl('one_head_dialog', _d));
                addActionOnehead(one_head_jQ.get(), _d);
                head_list_jQ.append(one_head_jQ);
            });
        });

        //点击“全部”
        all_jQ.click(function() {
            group_select_jQ.attr("disabled", false);
            all_jQ.addClass('active');
            selected_jQ.removeClass('active');
            group_select_jQ.change();
        });

        //初始化页面
        group_select_jQ.change();
    };


    //========================================分组操作：创建、修改、删除========================================

    //创建、修改、删除按钮
    var displayManageGroup = function() {

        title_jQ.html(cur_group_name);
        var group_info = { "id": cur_group_id, "name": cur_group_name };

        if (cur_group_name.contains("全部") || cur_group_name.contains("未分组")) {
            create_group_jQ.removeClass('btn_off').bind('click', function() { createGroup(group_info); });
            del_group_jQ.addClass('btn_off').unbind('click');
            edit_group_jQ.addClass('btn_off').unbind('click');
        } else {
            create_group_jQ.addClass('btn_off').unbind('click');
            del_group_jQ.removeClass('btn_off').bind('click', function() { delGroup(group_info); });
            edit_group_jQ.removeClass('btn_off').bind('click', function() { editGroup(group_info); });
        }

        group_op_jQ.show();
    };

    //创建分组
    var createGroup = function() {
        Dialog.show('newgroup_dialog', {
            'child_html': MPT.getTmpl('newgroup_dialog'),
            'width': 510,
            'height': 570,
            'cache': false,
            'success': function(_dlg) {
                var submit_jQ = $('.e_submit', _dlg);
                var cancel_jQ = $('.e_cancel', _dlg);
                var group_input_jQ = $('.e_group_input', _dlg);

                submit_jQ.click(function() {
                    var gname = group_input_jQ.val();
                    var data = { "groupName": gname, "targetIds": selected_ids.join(',') };

                    //创建分组
                    Backend.addFollowGroup(data, function(_resp) {
                        if (Backend.dataValidate(_resp)) {
                            //定位到新分组
                            displayGroupList(function() {
                                group_list_jQ.find('a[gid=' + _resp.data.groupID + ']').click();
                            });
                            Dialog.hide();

                        } else {
                            Tip.show("创建分组失败");
                        }
                    }, function() {
                        Tip.show("创建分组失败");
                    });
                });

                cancel_jQ.click(function() {
                    Dialog.hide();
                });

                displayFriendDialog(_dlg);
                Util.KeyBoardMonitor($(_dlg), 13, function() { submit_jQ.click(); });
            }
        });
    };


    //编辑分组
    var editGroup = function(_group) {
        Dialog.show('editgroup_dialog', {
            'child_html': MPT.getTmpl('editgroup_dialog', _group),
            'width': 510,
            'height': 570,
            'cache': false,
            'success': function(_dlg) {
                var submit_jQ = $('.e_submit', _dlg);
                var cancel_jQ = $('.e_cancel', _dlg);
                var group_input_jQ = $('.e_group_input', _dlg);

                submit_jQ.click(function() {

                    //修改分组名称
                    var data = { "groupId": _group.id, "groupName": group_input_jQ.val() };
                    Backend.modifyFollowGroupName(data, function(_resp) {
                        if (Backend.resultValidate(_resp)) {

                            //重新定位到原分组
                            displayGroupList(function() {
                                group_list_jQ.find('a[gid=' + _group.id + ']').click();
                            });
                            Dialog.hide();
                        } else {
                            Tip.show("编辑分组失败");
                        }
                    }, function() {
                        Tip.show("编辑分组失败");
                    });

                    //移动好友
                    if (selected_ids.length > 0) {
                        var data = { "follow_source_group": 0, "follow_target_group": _group.id, "targetUidStr": selected_ids.join('$') };
                        Backend.moveFollowGroupOneUserToMoreGroup(data, function(_resp) {
                            if (Backend.resultValidate(_resp)) {

                            } else {
                                Tip.show("移动好友失败");
                            }
                        }, function() {
                            Tip.show("移动好友失败");
                        });
                    }
                });

                cancel_jQ.click(function() {
                    Dialog.hide();
                });

                displayFriendDialog(_dlg);
                Util.KeyBoardMonitor($(_dlg), 13, function() { submit_jQ.click(); });
            }
        });
    };


    //删除分组
    var delGroup = function(_group) {

        Dialog.show('delgroup_dialog', {
            'child_html': MPT.getTmpl('delgroup_dialog', _group),
            'width': 360,
            'height': 190,
            'cache': false,
            'success': function(_dlg) {
                var submit_jQ = $('.e_submit', _dlg);
                var cancel_jQ = $('.e_cancel', _dlg);

                submit_jQ.click(function() {
                    var data = { "groupID": _group.id };

                    Backend.deleteFollowGroup(data, function(_resp) {
                        if (Backend.resultValidate(_resp)) {
                            //定位到全部好友
                            displayGroupList(function() {
                                group_list_jQ.find('a').eq(0).click();
                            });
                            Dialog.hide();
                        }
                    });
                });

                cancel_jQ.click(function() {
                    Dialog.hide();
                });

                Util.KeyBoardMonitor($(_dlg), 13, function() { submit_jQ.click(); });
            }
        });
    };

    //========================================搜索好友========================================



    //========================================页面初始化========================================

    var initialize = function() {

        Tab.switchFriend();

        displayGroupList(function() {
            addActionGroupTitle();
            var tab_name = window.location.hash.split('/')[2];
            if (tab_name == "follow") {
                group_list_jQ.children().eq(0).click();
            } else if (tab_name == "fan") {
                follow_me_jQ.click();
            }
        });

        sort_jQ.hover(function() {
            sort_jQ.addClass('active');
            sort_list_jQ.show();
        }, function() {
            sort_jQ.removeClass('active');
            sort_list_jQ.hide();
        });

        sort_list_jQ.find('a').click(function() {
            order_type = parseInt($(this).attr("order"));
            sort_list_jQ.find('a').removeClass('on');
            $(this).addClass('on');
            displayFriendList(1);
        });
    };

    initialize();
});

